import 'dart:math';

import 'package:acgn_pioneer/models/comment_model.dart';
import 'package:acgn_pioneer/widgets/reader/mixins/_index.dart';
import 'package:acgn_pioneer/widgets/reader/services/sr_comment.dart';
import 'package:flutter/widgets.dart';
import '../../../public.dart';
import '../_index.dart';
import 'utils.dart';

typedef CommentTapCallback = void Function(CommentModel model);

/// 评论子节点
class ReaderCommentItem extends StatefulWidget {
  final CommentModel commentModel;
  final ComicModel comicModel;
  final ChapterModel chapterModel;

  final bool isReply; // 是否回复模式，此模式不显示回复按钮

  ReaderCommentItem(
      {Key key,
      this.commentModel,
      this.comicModel,
      this.chapterModel,
      this.isReply = false})
      : super(key: key);

  @override
  ReaderCommentItemState createState() => new ReaderCommentItemState();
}

class ReaderCommentItemState extends State<ReaderCommentItem>
    with ReaderWidgetBase {
  final Color gray = ColorUtil.rgba(255, 255, 255, 0.6); // 普通色
  final Color lightColor = ColorUtil.rgba(255, 215, 59, 1); // 亮色
  ReaderCommentService readerCommentService = ReaderCommentService();

  @override
  Widget build(BuildContext context) {
    var model = widget.commentModel;

    return Container(
      padding: EdgeInsets.only(top: 20),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ClipRRect(
              borderRadius: BorderRadius.circular(40),
              child: ImagesNetworkComponent(
                  StringUtil.getUserId(model.userIdentifier),
                  placeholder: AppConfig.ASSETS_PATH + 'mrtx_qumh88.png',
                  width: 40,
                  height: 40)),
          SizedBox(width: 8),
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    model.uName,
                    style: TextStyle(
                        color: ColorUtil.rgba(255, 255, 255, 0.8),
                        fontSize: 12),
                  ),
                  SizedBox(
                    width: 6,
                  ),
                  Text(StringUtil.formatDate(model.createTime, 'yyyy.MM.dd'),
                      style: TextStyle(
                          color: ColorUtil.rgba(255, 255, 255, 0.4),
                          fontSize: 12))
                ],
              ),
              Container(
                margin: EdgeInsets.only(top: 10, bottom: 10),
                child: Text(model.content,
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: ColorUtil.rgba(255, 255, 255, 0.8),
                        fontSize: 14)),
              ),
              widget.isReply ? SizedBox.shrink() : buildReplyContainer(model),
              DefaultTextStyle.merge(
                  style: TextStyle(color: gray, fontSize: 12),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        buildChapterName(model.relateId),
                        Row(
                          children: [
                            widget.isReply
                                ? SizedBox.shrink()
                                : GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      CommentUtil.showInput(
                                          context,
                                          (context) => PopInputBoxComponent(
                                                  child: ReaderCommentInput(
                                                chapterModel:
                                                    widget.chapterModel,
                                                isComicType: false,
                                                placeholder: '回复：' +
                                                    widget.commentModel.uName,
                                              )));
                                    },
                                    child: Row(
                                      children: [
                                        Text('回复'),
                                        SizedBox(width: 4),
                                        SVG.icon('reader_comment', color: gray)
                                      ],
                                    )),
                            SizedBox(width: 20),
                            GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  addCommentSupport();
                                },
                                child: Row(
                                  children: [
                                    Text(
                                        model.supportCount == 0
                                            ? '送花'
                                            : model.supportCount.toString(),
                                        style: TextStyle(
                                            color: model.isSupport
                                                ? lightColor
                                                : gray)),
                                    SizedBox(width: 4),
                                    SVG.icon('reader_flower',
                                        color:
                                            model.isSupport ? lightColor : gray)
                                  ],
                                ))
                          ],
                        )
                      ]))
            ],
          ))
        ],
      ),
    );
  }

  // 构建子评论容器
  buildReplyContainer(CommentModel commentModel) {
    if (commentModel.lstChildren.length == 0) {
      return Container();
    }
    return GestureDetector(
        onTap: () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => ReaderCommentReply(
                        commentModel: commentModel,
                        comicModel: widget.comicModel,
                        chapterModel: widget.chapterModel,
                      )));
        },
        child: Container(
            margin: EdgeInsets.only(bottom: 10),
            width: double.infinity,
            decoration: BoxDecoration(
              color: ColorUtil.rgba(40, 40, 56, 1),
              borderRadius: BorderRadius.all(Radius.circular(4.0)),
            ),
            padding: EdgeInsets.all(12),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: buildReplyItem(commentModel))));
  }

  // 构建子评论
  buildReplyItem(CommentModel commentModel) {
    List<Widget> lst = [];
    int len = commentModel.lstChildren.length;
    commentModel.lstChildren.getRange(0, min(len, 2)).forEach((ele) {
      lst.add(Container(
          padding: EdgeInsets.only(bottom: 10),
          child: Text.rich(TextSpan(children: [
            TextSpan(
                text: ele.uName + '：',
                style: TextStyle(fontSize: 12, color: Colors.white)),
            TextSpan(
                text: ele.content,
                style: TextStyle(
                    color: ColorUtil.rgba(255, 255, 255, 0.8), fontSize: 12))
          ]))));
    });
    if (len > 2) {
      lst.add(Row(
        children: [
          Text(
            '共有$len条评论',
            style: TextStyle(color: lightColor, fontSize: 12),
          ),
          SVG.icon(
            'arrow_right',
            size: 12,
            color: lightColor,
          )
        ],
      ));
    }
    return lst;
  }

  // 构建章节名称
  buildChapterName(int chapterId) {
    if (chapterId == 0) {
      return Container();
    }

    return Container(
      padding: EdgeInsets.only(right: 20),
      constraints: BoxConstraints(minWidth: 180, maxWidth: 180),
      child: Text(
        widget.comicModel.chapters
            .firstWhere((ele) => ele.id == chapterId)
            .name,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  addCommentSupport() async {
    var status = widget.commentModel.isSupport ? 0 : 1;
    var count = widget.commentModel.supportCount;
    user = Provider.of<UserProvider>(context, listen: false).data;
    var comic = widget.comicModel;
    bool re = await readerCommentService.addCommentSupport(
        CommentModel(
            fatherId: widget.commentModel.id,
            ssid: comic.id,
            userIdentifier: user.uid),
        status);
    if (re) {
      widget.commentModel.isSupport = !widget.commentModel.isSupport;
      widget.commentModel.supportCount = status == 0 ? count - 1 : count + 1;
      setState(() {});
    }
  }
}
